
package org.jetnuke.dao.generic;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.jforum.JForumExecutionContext;
import net.jforum.dao.generic.AutoKeys;
import net.jforum.util.preferences.SystemGlobals;

import org.jetnuke.entities.StoryCheck;

public class GenericStoryCheckDAO extends AutoKeys implements
		org.jetnuke.dao.StoryCheckDAO {

	/* (non-Javadoc)
	 * @see org.jetnuke.model.StoryCheckModel#retrieveByPK(int)
	 */
	public StoryCheck retrieveByPK(int id) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see org.jetnuke.model.StoryCheckModel#addNew(org.jetnuke.entities.StoryCheck)
	 */
	public int addNew(StoryCheck check) throws Exception {
		PreparedStatement p = this.getStatementForAutoKeys("StoryCheckModel.addNew");
		this.setAutoGeneratedKeysQuery(SystemGlobals.getSql("StoryCheckModel.lastGeneratedStoryCheckID"));
		initNewStoryCheck(check, p);
		
		int id = this.executeAutoKeysQuery(p);
				
		return id;
	}

	/**
	 * @param check
	 * @param p
	 */
	private void initNewStoryCheck(StoryCheck check, PreparedStatement p) throws Exception {
		p.setString(1,check.getIP());
		p.setInt(2,check.getSTORY_ID());
		p.setTimestamp(3,new Timestamp(check.getTIME().getTime()));
		
		
	}

	/* (non-Javadoc)
	 * @see org.jetnuke.model.StoryCheckModel#deleteTimeLessThen(java.util.Date)
	 */
	public void deleteTimeLessThen(Date dt1) throws Exception {
		PreparedStatement p= JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("StoryCheckModel.deleteTimeLessThen"));
		p.setTimestamp(1,new Timestamp(dt1.getTime()));
		p.executeUpdate();
		p.close();
		
	}

	/* (non-Javadoc)
	 * @see org.jetnuke.model.StoryCheckModel#selectByIP_STORY(int)
	 */
	public List selectByIP_STORY(String ip,int id) throws Exception {
		PreparedStatement p= JForumExecutionContext.getConnection().prepareStatement(SystemGlobals.getSql("StoryCheckModel.selectByIP_STORY"));
		p.setString(1,ip);
		p.setInt(2,id);
		ResultSet rs = p.executeQuery();
		List list = this.processSelectAll(rs);
		rs.close();
		p.close();
		
		return list;
	}

	/**
	 * @param rs
	 * @return
	 */
	private List processSelectAll(ResultSet rs)throws Exception {
		List list = new ArrayList();
		while (rs.next()) {
			StoryCheck u = new StoryCheck();
			fillStoryCheckFromResultSet(u,rs);			
			list.add(u);
		}
		
		return list;
	}

	/**
	 * @param u
	 * @param rs
	 */
	protected void fillStoryCheckFromResultSet(StoryCheck u, ResultSet rs) throws Exception {
		u.setID(rs.getInt("ID"));
		u.setIP(rs.getString("IP"));
		u.setSTORY_ID(rs.getInt("STORY_ID"));
		u.setTIME(rs.getTimestamp("TIME"));
		
	}

}
